import { BusinessError } from '@kit.BasicServicesKit';
import { OhosDisplayInfo } from './workers/OhosDisplayInfo';
import { WindowUtils } from './utils/WindowUtils';
import window from '@ohos.window';
import display from '@ohos.display';


export function RegisterSafeAreaWidth()
{
  const register = {};
  register["SafeAreaWidth"] =  new SafeAreaWidth();
  return register;
}

export class SafeAreaWidth {
  private height: number; // 用于存储计算的高度

  public calculateSafeAreaWidth(callback:Function): void {
    console.log("enter successfully" );
    // let windowClass: window.Window = globalThis.windowStage.getMainWindow();
    // if (windowClass == null || windowClass == undefined)
    //   return null;
    // let avoidArea: window.AvoidArea = windowClass.getWindowAvoidArea(window.AvoidAreaType.TYPE_CUTOUT);
    // console.log("###avoidArea:" + JSON.stringify(avoidArea));
    //
    //

    let displayClass = null;
    displayClass = display.getDefaultDisplaySync();
    let screen_width = displayClass.width;
    console.info('Screen Width:', screen_width);
    // 这里使用一个立即调用的函数表达式 (IIFE) 来处理异步逻辑
    displayClass.getCutoutInfo((err, data) => {
      if (err.code) {
        console.error('Failed to get cutoutInfo. Code: ' + JSON.stringify(err));
        return;
      }
      console.info('Succeeded in getting cutoutInfo. data: ' + JSON.stringify(data));
      let avoidarea_left = data.boundingRects[0].left;
      let avoidarea_width = data.boundingRects[0].width;

      console.info('Avoid Area Left:', avoidarea_left);
      console.info('Avoid Area Width:', avoidarea_width);


      let value1 = screen_width - avoidarea_left; // screen.width - left
      let value2 = avoidarea_left + avoidarea_width; // left + width
      // 取两者间的较小值
      callback(Math.min(value1, value2));
    });
    // 这里返回一个默认值，实际的 height 值在异步回调中更新

  }
}

